<?php
declare (strict_types=1);

namespace app\store\model;

use app\common\library\helper;
use app\store\service\store\User as StoreUserService;
use app\store\validate\Supplier as ValidateSupplier;
use app\common\model\Supplier as SupplierModel;
use app\store\model\SupplierCategory as SupplierCategoryModel;
use app\store\model\SupplierBank as SupplierBankModel;
use cores\exception\BaseException;
use think\contract\Arrayable;

/**
 * 供应商模型
 * Class Goods
 * @package app\store\model
 */
class Supplier extends SupplierModel
{
    /**
     * 获取供应商详情
     * @param int $goodsId
     * @return mixed
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail(int $supplierId)
    {
        // 关联查询
        $with = ['category', 'bank.image', 'legalCardImg', 'licenseImg'];
        // 获取供应商记录
        $supplierInfo = static::detail($supplierId, $with);
        //var_dump($supplierInfo->toArray());exit;
        empty($supplierInfo) && throwError('很抱歉，供应商信息不存在');
        //var_dump($supplierInfo->toArray());exit;
        if ($supplierInfo['category']) {
            $supplierInfo['business_category'] = array_column($supplierInfo['category']->toArray(), 'category_id');
            unset($supplierInfo['category']);
        }
        $supplierInfo['license_date']       = $supplierInfo['license_date'] > 0 ? date('Y-m-d', $supplierInfo['license_date']) : '';
        $supplierInfo['license_start_time'] = $supplierInfo['license_date'] > 0 ? date('Y-m-d', $supplierInfo['license_start_time']) : '';
        $supplierInfo['license_end_time']   = $supplierInfo['license_date'] > 0 ? date('Y-m-d', $supplierInfo['license_end_time']) : '';

        $supplierInfo['bank_name']      = $supplierInfo['bank'][0]['bank_name'] ?? '';
        $supplierInfo['bank_account']   = $supplierInfo['bank'][0]['bank_account'] ?? '';
        $supplierInfo['sub_branch']     = $supplierInfo['bank'][0]['sub_branch'] ?? '';
        $supplierInfo['bank_card']      = $supplierInfo['bank'][0]['bank_card'] ?? '';
        $supplierInfo['permit_img']     = $supplierInfo['bank'][0]['image']['file_id'] ?? '';
        $supplierInfo['permitImg']      = $supplierInfo['bank'][0]['image'] ?? '';
        $supplierInfo['permit_img_url'] = $supplierInfo['bank'][0]['image']['preview_url'] ?? '';
        unset($supplierInfo['bank']);
        $supplierInfo['legal_card_img_url'] = $supplierInfo['legalCardImg']['preview_url'] ?? '';
        $supplierInfo['license_img_url']    = $supplierInfo['licenseImg']['preview_url'] ?? '';
        return $supplierInfo;
    }

    /**
     * 添加供应商
     * @param array $data
     * @return bool
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(array $data): bool
    {
        // 数据验证
        $validate = new ValidateSupplier;
        if (!$validate->check($data)) {
            throwError($validate->getError());
        }
        $supplierInfo = static::get(['business_name' => $data['business_name']]);
        !empty($supplierInfo) && throwError('该供应商信息已存在，不能重复添加');

        $data['store_id']           = self::$storeId;
        $data['license_date']       = !empty($data['license_date']) ? str2time_date($data['license_date']) : time();
        $data['license_start_time'] = !empty($data['license_start_time']) ? str2time_date($data['license_start_time']) : time();
        $data['license_end_time']   = !empty($data['license_end_time']) ? str2time_date($data['license_end_time']) : time();

        // 事务处理
        $this->transaction(function () use ($data) {
            $bank_info['bank_name']    = $data['bank_name'];
            $bank_info['bank_account'] = $data['bank_account'];
            $bank_info['sub_branch']   = $data['sub_branch'];
            $bank_info['bank_card']    = $data['bank_card'];
            $bank_info['permit_img']   = $data['permit_img'];
            $bank_info['store_id']     = self::$storeId;
            // 添加供应商
            $this->save($data);
            // 新增供应商与分类关联
            SupplierCategoryModel::increased((int)$this['supplier_id'], $data['business_category']);
            // 新增供应商银行卡信息
            SupplierBankModel::add((int)$this['supplier_id'], $bank_info);
        });
        return true;
    }

    /**
     * 编辑供应商
     * @param array $data
     * @return bool
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(array $data): bool
    {
        // 数据验证
        $validate = new ValidateSupplier;
        if (!$validate->check($data)) {
            throwError($validate->getError());
        }
        $supplierInfo = $this->where('supplier_id', '<>', $this['supplier_id'])
            ->where('business_name', '=', $data['business_name'])
            ->select()->toArray();
        //echo $this->getLastSql();exit;
        !empty($supplierInfo) && throwError('该供应商信息已存在，不能修改');

        $data['license_date']       = !empty($data['license_date']) ? str2time_date($data['license_date']) : time();
        $data['license_start_time'] = !empty($data['license_start_time']) ? str2time_date($data['license_start_time']) : time();
        $data['license_end_time']   = !empty($data['license_end_time']) ? str2time_date($data['license_end_time']) : time();
        // 事务处理
        $this->transaction(function () use ($data) {
            $bank_info['bank_name']    = $data['bank_name'];
            $bank_info['bank_account'] = $data['bank_account'];
            $bank_info['sub_branch']   = $data['sub_branch'];
            $bank_info['bank_card']    = $data['bank_card'];
            $bank_info['permit_img']   = $data['permit_img'];
            $bank_info['store_id']     = self::$storeId;
            $data['status'] = 0;
            $data['remarks'] = '';
            // 更新供应商
            $this->save($data);
            // 更新供应商与分类关联
            SupplierCategoryModel::updates((int)$this['supplier_id'], $data['business_category']);
            // 新增供应商银行卡信息
            SupplierBankModel::edit((int)$this['supplier_id'], $bank_info);
        });
        return true;
    }

    /**
     * 修改供应商状态
     * @param array $data
     * @return bool|false
     */
    public function setStatus($data)
    {
        if (empty($data['status']) || empty($data['supplierIds'])) {
            return false;
        }
        $user_info = StoreUserService::getLoginInfo()['user'];
        $remarks = $data['remarks'] ?? '';
        return static::updateBase(['status' => $data['status'], 'remarks' => $remarks, 'admin_id' => $user_info['store_user_id']], [['supplier_id', 'in', $data['supplierIds']]]);
    }

    /**
     * 供应商模糊查询
     * @param array $SupplierIds 供应商id集
     * @return array
     */

    /**
     * 供应商模糊查询
     * @param $supplierName
     * @return array
     */
    public function getListBySupplierName($supplierName='')
    {
        $query = $this->getNewQuery();
        if($supplierName){
            $query->where('business_name', 'like', "%{$supplierName}%");
        }
        return $query->field('supplier_id,business_name')
            ->where(['status' => 1])
            ->select();
    }
}
